<template>
  <div class="article-display">
    <div class="bac-container flex" :style="{
      backgroundImage: `url(${article.cover_url || 'http://42.192.127.112/assets/images/article_cover.jpg'})`
    }">
      <div class="main-box">
        <h1>{{article.headline}}</h1>
        <h5>{{article.outline}}</h5>
      </div>
    </div>
    <AuthorBox :data="article.user_model" />
    <div class="tag-box flex">
      <Tag fill="#ff4545" class="icon icon-tag"/>
      <!-- <div class="tag" v-for="tag of tags" :key="tag.id">
        {{tag.name}}
      </div> -->
      <router-link tag="div" class="tag" v-for="tag of tags" :key="tag.id" :to="{
        name: 'TagDisplay', params: {tagId: tag.id}
      }">
        {{tag.name}}
      </router-link>

      <router-link tag="div" class="function-tag" v-if="article.functionality_model" :to="{
        name: 'FunctionalityDisplay', params: {functionalityId: article.functionality_model.id}
      }">
        <span>{{article.functionality_model.name}}</span> 
      </router-link>
    </div>

    <div id="editor-view">
      <!-- toolbarsFlag 工具栏是否展示  defaultOpen 默认预览 subfield 单双栏-->
        <mavon-editor style="height: 100%"
          :transition="false" 
          :toolbarsFlag="false"  
          :defaultOpen="'preview'"
          :subfield="false" 
          :value="article.content" :boxShadowStyle="'none'" :previewBackground="'transparent'"
        ></mavon-editor>
    </div>

    <div class="bottom-box flex">
      <span class="icon-box" @click="toLikeArticle"><Like :fill="liked? '#FF4545' : 'black'" class="icon" /> {{like_times}} </span>
      <span class="icon-box" @click="toCollectArticle"><Collection :fill="collected? '#FF4545' : 'black'"  class="icon" /> {{collect_times}} </span>
      <span class="icon-box"><Look class="icon icon-look"/> {{article.look_times}} </span>
    </div>
  </div>
</template>

<script>
//components 组件
import AuthorBox from '__COMPONENTS__/author_box/AuthorBox.vue'
import Like from '__SVG__/like.svg'
import Collection from '__SVG__/collection.svg'
import Look from '__SVG__/look.svg'
import Tag from '__SVG__/tag.svg'
//公共资源
import Vue from 'vue'
import NProgress from 'nprogress' 
//service api
import { getArticleById, lookArticle } from '__SERVICE__/article.js'
import { isLiked, likeArticle } from '__SERVICE__/like.js'
import { isCollected, collectArticle } from '__SERVICE__/collection.js'
//vuex
import { GET_TAG_TREE,  SAVE_USER_INFO } from '__STORE__/operation-type'
//mixin
import paramsDispose from '__CORE__/mixins/paramsDispose.js'
import MavonEditorMxin from '__COMPONENTS__/mavon_editor/base-mixin.js'
const {isEffective} = paramsDispose

export default {
  name: 'ArticleDisplay',
  props: ['articleId', 'id'],
  mixins: [paramsDispose, MavonEditorMxin],
  components: { AuthorBox, Like, Collection, Look, Tag },
  computed: {
    tags() {
      const tags = this.$store.getters.tags
      return this.article.tag_ids ? JSON.parse(this.article.tag_ids).slice(0,3).map((id)=>{
        return tags.find(function(tag){
          return tag.id == id
        })
      }) : {}
    },
    deadUserInfo() {
      return this.$store.state.user.deadUserInfo
    }
  },
  data:()=>({
    article: {},
    like_times: 0,
    collect_times: 0,
    collected: false,
    liked: false,
  }),
  methods: {
    //处理props的id end
    async getArticleById() {
      try {
        this.$Loading.show()
        const result = await getArticleById(this.articleId)
        this.$Loading.hidden()
        const {data: {article}, message} = result
        this.article = Object.freeze(article)//注意冻结属性
        this.like_times = article.like_times
        this.collect_times = article.collect_times
      }catch(e) {
        console.log(e.message)
        Vue.prototype.$Notice.error({
          title: '操作错误',
          desc: 'URL需要是合理值',
          duration: 3000
        })
        this.$router.push({name: 'Home'})
      }
    },
    async getTags() {
      try {
        const dataRsource = this.$store.state.globalConfig
        //如果没有等待 获取数据
        if(!dataRsource.tagTree ) await this.$store.dispatch(GET_TAG_TREE)
        //成功获取数据
        const tagclasses = dataRsource.tagTree 
        this.tagTree = tagclasses
      }catch(e) {
        console.log(e.message)
      }
    },
    //id有效要做的事 start
    idEffectiveToDo(newValue, oldValue) {
      this.getArticleById()//更新之后
    },
    //id有效要做的事 end

    //id无效要做的事 start
    idNoneffectiveToDo(newValue, oldValue) {
      this.$router.push({name: 'ArticleDisplay', params: {articleId: oldValue}})
    },
    //id无效要做的事 end

    //浏览文章
    async lookArticle() {
      const result = await lookArticle(this.articleId)
    },
    //点赞文章
    async toLikeArticle() {
      const { user_id, access_token } = this.deadUserInfo
      if(!user_id || !access_token) {
        this.$Notice.error({
          title: '账户无效',
          desc: '请确认是否登入',
          duration: 3000
        })
        return
      }
      try {
        this.like_times = this.like_times + (this.liked ? -1 : 1)
        this.liked = !this.liked
        const result = await likeArticle({
          article_id: this.articleId, user_id, access_token, likeType: + this.liked
        })
        this.$store.dispatch(SAVE_USER_INFO, {
          access_token: result.data.access_token
        })
      }catch(e) {
        console.log(e.message)
        this.like_times = this.like_times + (this.liked ? -1 : 1)
        this.liked = !this.liked
      }
    },
    //收藏文章
    async toCollectArticle() {
      const { user_id, access_token } = this.deadUserInfo
      if(!user_id || !access_token) {
        this.$Notice.error({
          title: '账户无效',
          desc: '请确认是否登入',
          duration: 3000
        })
        return
      }
      try {
        this.collect_times = this.collect_times + (this.collected ? -1 : 1)
        this.collected = !this.collected
        const result = await collectArticle({
          article_id: this.articleId, user_id, access_token, collectionType: +this.collected
        })
        this.$store.dispatch(SAVE_USER_INFO, {
          access_token: result.data.access_token
        })
      }catch(e) {
        console.log(e.message)
        this.collect_times = this.collect_times + (this.collected ? -1 : 1)
        this.collected = !this.collected
      }
    },
    //检查是否能点击
    async isLiked() {
      const { user_id, access_token } = this.deadUserInfo
      const article_id = this.articleId
      const result = await isLiked(article_id, user_id)
      const { data: {liked} } = result
      this.liked = liked
    },
    async isCollected() {
      const { user_id, access_token } = this.deadUserInfo
      const article_id = this.articleId
      const result = await isCollected(article_id, user_id)
      const { data: {collected} } = result
      this.collected = collected
    }
  },
  created() {
    this.getTags()//获取 标签树
    this.getArticleById()//更新之后
    //如果登入请求是否点赞
    if(this.deadUserInfo.user_id){
      this.isLiked()
      this.isCollected()
    } 
  },
  mounted() {
    this.myTimerOne = setTimeout(()=>{
      this.lookArticle()
    }, 5000)
    this.$once("hook:beforeDestroy", ()=>{
      clearTimeout(this.myTimerOne)
    })
  }
}
</script>

<style lang="less">
  @import url('__CSS__/article_display/article_display.less');
  @import url('__COMPONENTS__/mavon_editor/base_style.less');
</style>